package com.cai.dao.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cai.dao.DbUtil;
import com.cai.dao.UserTopicDao;
import com.cai.pojo.DetailedTopic;
import com.cai.pojo.TopicHelp;

import java.util.List;

/**
 * @author RuoLi
 */
public class UserTopicDaoImpl implements UserTopicDao {
    int maxTopicCount;
    int trueCount;

    private void getPercentage(int userAccount) {
        DbUtil dbUtil = new DbUtil();
        //查看答题次数
        String sqlMaxCount = "SELECT MAX(replied_count) FROM user_topic WHERE user_account=?";
        maxTopicCount = Integer.parseInt(dbUtil.selectContent(sqlMaxCount, new String[]{String.valueOf(userAccount)}));
        //查看回答正确次数
        String sqlTrueCount = "SELECT MAX(replied_true_count) FROM user_topic WHERE user_account=?";
        trueCount = Integer.parseInt(dbUtil.selectContent(sqlTrueCount, new String[]{String.valueOf(userAccount)}));
    }

    @Override
    public String userTopicInfo(int userAccount) {
        return "";
    }

    @Override
    public int getThisTopicIsFavorites(int userAccount, int detailedTopicId) {
        String sql = "SELECT favorites FROM user_topic WHERE user_account=? AND detailed_topic_id=?";
        String[] params = {String.valueOf(userAccount), String.valueOf(detailedTopicId)};
        return DbUtil.selectCountIsExist(sql, params);
    }

    @Override
    public int queryThisTopicIsExist(int userAccount, int detailedTopicId) {
        int count;
        String sql = "SELECT COUNT(*) FROM user_topic WHERE user_account=? AND detailed_topic_id=?";
        count = DbUtil.selectCountIsExist(sql, new String[]{String.valueOf(userAccount), String.valueOf(detailedTopicId)});
        return count;
    }

    @Override
    public int updateTopicFavorites(int userAccount, int detailedTopicId, int favorites) {
        int status;
        String sql;
        int count = queryThisTopicIsExist(userAccount, detailedTopicId);
        if (count == 0) {
            //执行添加
            sql = "INSERT INTO `online_quiz_website`.`user_topic`(`user_account`, `detailed_topic_id`,`favorites`) VALUES (?,?,?)";
            status = DbUtil.updateContent(sql, new Integer[]{userAccount, detailedTopicId, favorites});
        } else {
            sql = "UPDATE `online_quiz_website`.`user_topic` SET `favorites` = ? WHERE `user_account` = ? AND `detailed_topic_id` = ?";
            status = DbUtil.updateContent(sql, new Integer[]{favorites, userAccount, detailedTopicId});
        }
        return status;

    }

    @Override
    public int updateLogUserTopicData(int userAccount, int detailedTopicId, String topicAnswer, String userAnswer, int topicStatus) {
        int status;
        int isExist = queryThisTopicIsExist(userAccount, detailedTopicId);
        getPercentage(userAccount);
        //查看是否有用户答题数据
        if (isExist == 0) {
            String sql = "INSERT INTO `online_quiz_website`.`user_topic`" +
                    "(`user_account`, `detailed_topic_id`, `topic_answer`, `user_answer`,replied_count,replied_true_count) " +
                    "VALUES (?,?,?,?,?,?)";
            //如果没有,查看回答是否正确
            if (topicAnswer.equals(userAnswer)) {
                status = DbUtil.updateContent(sql, new Object[]{userAccount, detailedTopicId, topicAnswer, userAnswer, maxTopicCount + 1, trueCount + 1});
            } else {
                status = DbUtil.updateContent(sql, new Object[]{userAccount, detailedTopicId, topicAnswer, userAnswer, maxTopicCount + 1, trueCount});
            }
            //如果有用户数据
        } else {
            String sql = "UPDATE `online_quiz_website`.`user_topic` SET " +
                    "`topic_answer` = ?, `user_answer` = ?, `replied_count` = ?, `replied_true_count` = ? " +
                    "WHERE `user_account` = ? AND `detailed_topic_id`=? ";
            //如果回答正确
            if (topicAnswer.equals(userAnswer)) {
                status = DbUtil.updateContent(sql, new Object[]{topicAnswer, userAnswer, maxTopicCount + 1, trueCount + 1, userAccount, detailedTopicId});
            } else {
                status = DbUtil.updateContent(sql, new Object[]{topicAnswer, userAnswer, maxTopicCount + 1, trueCount, userAccount, detailedTopicId});
            }
        }
        return status;
    }

    @Override
    public String getPercentageData(int userAccount) {
        DbUtil dbUtil = new DbUtil();
        getPercentage(userAccount);
        //正确率
        float percentageTrue = ((float) trueCount / maxTopicCount) * 100;
        //答题率
        String sqlTopicCount = "SELECT count(detailed_topic_id) FROM detailed_topic";
        int topicCount = Integer.parseInt(dbUtil.selectContent(sqlTopicCount));
        String sqlUserTopicCount = "SELECT count(detailed_topic_id) FROM user_topic WHERE user_account=?";
        int userTopicCount = Integer.parseInt(dbUtil.selectContent(sqlUserTopicCount, new String[]{String.valueOf(userAccount)}));
        float percentage = ((float) userTopicCount / topicCount) * 100;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("percentageTrue", String.format("%.2f", percentageTrue));
        jsonObject.put("percentage", String.format("%.2f", percentage));
        return jsonObject.toString();
    }

    @Override
    @SuppressWarnings("unchecked")
    public String getUserFavoritesTopicInfo(int userAccount) {
        String sql = "SELECT detailed_topic_id,\n" +
                "(SELECT topic_title FROM detailed_topic WHERE detailed_topic.detailed_topic_id=user_topic.detailed_topic_id) AS topic_title,\n" +
                "(SELECT knowledge_point FROM topic WHERE topic.topic_id=(SELECT topic_id FROM detailed_topic WHERE detailed_topic.detailed_topic_id=user_topic.detailed_topic_id)) AS knowledge_point,\n" +
                "(SELECT topic_type FROM topic WHERE topic.topic_id=(SELECT topic_id FROM detailed_topic WHERE detailed_topic.detailed_topic_id=user_topic.detailed_topic_id)) AS topic_type,\n" +
                "(SELECT detailed_topic.frequency FROM detailed_topic WHERE user_topic.detailed_topic_id=detailed_topic.detailed_topic_id) AS frequency \n" +
                "FROM user_topic WHERE user_account=? AND favorites=1";
        List<DetailedTopic> list = (List<DetailedTopic>) DbUtil.getUserFavoritesTopicInfo(sql, userAccount);
        return getUserTopic(list);
    }


    @Override
    @SuppressWarnings("unchecked")
    public String getUserErrorTopicInfo(int userAccount) {
        String sql = "SELECT detailed_topic_id,\n" +
                "(SELECT topic_title FROM detailed_topic WHERE detailed_topic.detailed_topic_id=user_topic.detailed_topic_id) AS topic_title,\n" +
                "(SELECT knowledge_point FROM topic WHERE topic.topic_id=(SELECT topic_id FROM detailed_topic WHERE detailed_topic.detailed_topic_id=user_topic.detailed_topic_id)) AS knowledge_point,\n" +
                "(SELECT topic_type FROM topic WHERE topic.topic_id=(SELECT topic_id FROM detailed_topic WHERE detailed_topic.detailed_topic_id=user_topic.detailed_topic_id)) AS topic_type,\n" +
                "(SELECT detailed_topic.frequency FROM detailed_topic WHERE user_topic.detailed_topic_id=detailed_topic.detailed_topic_id) AS frequency \n" +
                "FROM user_topic WHERE user_account=? AND user_answer!=topic_answer";
        List<DetailedTopic> list = (List<DetailedTopic>) DbUtil.getUserErrorTopicInfo(sql, userAccount);
        return getUserTopic(list);
    }

    @Override
    @SuppressWarnings("unchecked")
    public String getUserHelpLog() {
        String sql = "SELECT tip_context FROM topic_help WHERE tip_title='帮助提示' AND tip_status=0";
        DbUtil dbUtil = new DbUtil();
        List<TopicHelp> list =(List<TopicHelp>) dbUtil.selectContent(sql, new String[]{}, TopicHelp.class);
        JSONArray jsonArray=new JSONArray();
        for (TopicHelp help : list
        ) {
            jsonArray.add(help.getTip_context());
        }
        return jsonArray.toString();
    }

    private String getUserTopic(List<DetailedTopic> list) {
        JSONArray jsonArray = new JSONArray();
        for (DetailedTopic topic : list
        ) {
            JSONObject object = new JSONObject();
            object.put("detailedTopicId", topic.getDetailed_topic_id());
            object.put("topic_title", topic.getTopic_title());
            object.put("frequency", topic.getFrequency());
            object.put("knowledge_point", topic.getTopic().getKnowledge_point());
            object.put("topic_type", topic.getTopic().getTopic_type());
            jsonArray.add(object);
        }
        return jsonArray.toJSONString();
    }
}
